package org.ezplatform.office.questionnaire.service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.ezplatform.core.dao.jpa.JpaBaseDao;
import org.ezplatform.core.service.BaseService;
import org.ezplatform.office.questionnaire.dao.QuestionnaireSetItemsDao;
import org.ezplatform.office.questionnaire.dao.QuestionnaireSetTopicDao;
import org.ezplatform.office.questionnaire.entity.QuestionnaireSetItems;
import org.ezplatform.office.questionnaire.entity.QuestionnaireSetTopic;
import org.ezplatform.office.questionnaire.util.JsonUtil;
import org.ezplatform.office.questionnaire.util.QuestionnaireUtils;
import org.ezplatform.util.JsonUtils;
import org.ezplatform.util.StringUtils;
import org.ezplatform.util.UuidUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service("QuestionnaireSetTopicService")
@Transactional
public class QuestionnaireSetTopicService extends BaseService<QuestionnaireSetTopic, String> {

	private final static Logger LOGGER = LoggerFactory.getLogger(QuestionnaireSetTopicService.class);

	@Autowired
	@Qualifier("questionnaireSetTopicDao")
	private QuestionnaireSetTopicDao topicDao;

	@Autowired
	@Qualifier("questionnaireSetItemsDao")
	private QuestionnaireSetItemsDao itemDao;

	@Override
	protected JpaBaseDao<QuestionnaireSetTopic, String> getEntityDao() {
		return topicDao;
	}

	/**
	 * 获取要保存的题目
	 * 
	 * @param map
	 *            题目实体map形式
	 * @param setId
	 *            题库Id
	 * @param topicType
	 *            题目类型：sinselect-单选、multiselect-多选、check-下拉、scale-量表、mulscale-矩阵量表、answer-问答、field-附件、paging-分页、illustrate-说明
	 * @return 题目实体集合
	 */
	public QuestionnaireSetTopic getSaveTopicInfo(Map<String, Object> map, String setId, String topicType) {
		QuestionnaireSetTopic topic = new QuestionnaireSetTopic();
		String topicName = (String) map.get("topic");
		String topicTxt = (String) map.get("topicTxt");
		String topicNo = (String) map.get("topicNo");
		String times = (String) map.get("times");
		if ("illustrate".equals(topicType) || "paging".equals(topicType)) {
			topicNo = "";
		} else if ("answer".equals(topicType) || "fillInBlanks".equals(topicType)) {
			topic.setTopicSetting(StringUtils.null2String(map.get("topicSetting")));
		} else {
			Map<String, Object> topicMap = (Map<String, Object>) map.get("topicSetting");
			String topicSetting = JsonUtil.mapToJson(topicMap);
			topic.setTopicSetting(topicSetting);
		}
		int sortNo = 0;
		if(map.get("dataSortNo") != null) {
			sortNo = Integer.parseInt(map.get("dataSortNo").toString());
		} 
		topic.setTopicName(topicName);
		topic.setTopicNameTxt(topicTxt);
		topic.setTopicNo(topicNo);
		topic.setSortNo(sortNo);
		topic.setTopicType(topicType);
		topic.setSetId(setId);
		topic.setTimes(times);
		String id = UuidUtils.UUID();
		topic.setId(id);
		return topic;
	}

	/**
	 * 根据题库Id删除题库题目
	 * 
	 * @param setId
	 *            题库Id
	 * @return 删除成功返回true
	 */
	public boolean deleteTopicBySetId(String setId) {
		topicDao.deleteTopicBySetId(setId);
		return true;
	}

	/**
	 * 根据题库Id删除题库题目
	 * 
	 * @param list
	 *            题库Id集合
	 * @return 删除成功返回true
	 */
	public boolean deleteTopicBySetId(List<String> list) {
		topicDao.deleteTopicBySetId(list);
		return true;
	}

	/**
	 * 根据题库Id查询题目Id集合
	 * 
	 * @param setId
	 *            题库Id
	 * @return 题目Id集合
	 */
	public List<String> getTopicIdBySetId(String setId) {
		return topicDao.getTopicIdBySetId(setId);
	}

	/**
	 * 根据题库Id集合查询题目Id集合
	 * 
	 * @param list
	 *            题库Id集合
	 * @return 题目Id集合
	 */
	public List<String> getTopicIdBySetId(List<String> list) {
		return topicDao.getTopicIdBySetId(list);
	}

	/**
	 * 获取题库题目信息
	 * 
	 * @param setId
	 *            题库Id
	 * @param userId
	 *            用户ID
	 * @param token
	 *            系统参数：TOKEN
	 * @return 题库题目实体集合
	 */
	public List<QuestionnaireSetTopic> getSetTopicList(String setId, String topicType, String topicName, String topicIds, String userId, String token) {
		List<QuestionnaireSetTopic> list = new ArrayList<>();
		List<QuestionnaireSetTopic> topicList = new ArrayList<>();
		StringBuffer sql = new StringBuffer();
		sql.append(" SELECT t.ID, t.set_id, t.topic_name, t.topic_name_txt, t.topic_no, t.topic_setting, t.topic_type, t.times, t.sort_no FROM oa_questionnaire_set_topic t WHERE t.set_id = :setId");
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("setId", setId);
		if (StringUtils.isNotBlank(topicType)) {
			sql.append(" AND t.topic_type = :topicType");
			paramMap.put("topicType", topicType);
		}
		if (StringUtils.isNotBlank(topicName)) {
			sql.append(" AND t.topic_name_txt LIKE :topicName");
			paramMap.put("topicName", "%"+topicName+"%");
		}
		if (StringUtils.isNotBlank(topicIds)) {
			sql.append(" AND t.ID IN (:topicIds)");
			paramMap.put("topicIds", Arrays.asList(topicIds.split(",")));
		}
		sql.append(" ORDER BY t.createdDate,t.sort_no");
		List<Map> mapList = super.findByListNativeQuery(sql.toString(), "", paramMap);
		if (CollectionUtils.isNotEmpty(mapList)) {
			int index = 0;
			for (Map map : mapList) {
				QuestionnaireSetTopic questionnaireSetTopic = new QuestionnaireSetTopic();
				questionnaireSetTopic.setId(map.get("ID").toString());
				questionnaireSetTopic.setSetId(map.get("set_id").toString());
				questionnaireSetTopic.setTopicName(StringUtils.null2String(map.get("topic_name")));
				questionnaireSetTopic.setTopicNameTxt(StringUtils.null2String(map.get("topic_name_txt")));
				questionnaireSetTopic.setTopicNo(String.valueOf(++index));
				questionnaireSetTopic.setTopicSetting(StringUtils.null2String(map.get("topic_setting")));
				questionnaireSetTopic.setTopicType(StringUtils.null2String(map.get("topic_type")));
				questionnaireSetTopic.setTimes(StringUtils.null2String(map.get("times")));
				questionnaireSetTopic.setSortNo(Integer.parseInt(StringUtils.null2String(map.get("sort_no"))));
				topicList.add(questionnaireSetTopic);
			}
		}
		for (int i = 0; i < topicList.size(); i++) {
			QuestionnaireSetTopic topic = topicList.get(i);
			String ruleTopicName = topic.getTopicName();
			if(!"".equals(StringUtils.null2String(ruleTopicName))){
				//ruleTopicName =ruleTopicName.replace("<p>", "").replace("</p>", "");
				topic.setRuleTopicName(ruleTopicName);
			}
			String topicSetting = StringUtils.null2String(topic.getTopicSetting());
			if (!"".equals(topicSetting)) {
				Map<String, Object> mapTopicSet = new HashMap<String, Object>();
				mapTopicSet = JsonUtils.readValue(topicSetting);
				if ("field".equals(topic.getTopicType())) {
					String extensions = "";
					if ("gif".equals(mapTopicSet.get("gif"))) {
						extensions += "gif" + ",";
					}
					if ("png".equals(mapTopicSet.get("png"))) {
						extensions += "png" + ",";
					}
					if ("jpg".equals(mapTopicSet.get("jpg"))) {
						extensions += "jpg" + ",";
					}
					if ("jpeg".equals(mapTopicSet.get("jpeg"))) {
						extensions += "jpeg" + ",";
					}
					if ("bmp".equals(mapTopicSet.get("bmp"))) {
						extensions += "bmp" + ",";
					}
					if ("doc".equals(mapTopicSet.get("doc"))) {
						extensions += "doc" + ",";
					}
					if ("docx".equals(mapTopicSet.get("docx"))) {
						extensions += "docx" + ",";
					}
					if ("pdf".equals(mapTopicSet.get("pdf"))) {
						extensions += "pdf" + ",";
					}
					if ("xls".equals(mapTopicSet.get("xls"))) {
						extensions += "xls" + ",";
					}
					if ("xlsx".equals(mapTopicSet.get("xlsx"))) {
						extensions += "xlsx" + ",";
					}
					if ("ppt".equals(mapTopicSet.get("ppt"))) {
						extensions += "ppt" + ",";
					}
					if ("pptx".equals(mapTopicSet.get("pptx"))) {
						extensions += "pptx" + ",";
					}
					if ("txt".equals(mapTopicSet.get("txt"))) {
						extensions += "txt" + ",";
					}
					if ("rar".equals(mapTopicSet.get("rar"))) {
						extensions += "rar" + ",";
					}
					if ("zip".equals(mapTopicSet.get("zip"))) {
						extensions += "zip" + ",";
					}
					if ("gzip".equals(mapTopicSet.get("gzip"))) {
						extensions += "gzip" + ",";
					}
					if (extensions.endsWith(",")) {
						extensions = extensions.substring(0, extensions.length() - 1);
					}
					if (!"".equals(extensions)) {
						mapTopicSet.put("upload", "true");
					} else {
						mapTopicSet.put("upload", "false");
					}
					mapTopicSet.put("extensions", extensions);
				}
				topic.setSettingMap(mapTopicSet);
			}
			List<QuestionnaireSetItems> itemsListObj = itemDao.getItemsByTopicId(topic.getId());
			List<QuestionnaireSetItems> itemsList = new ArrayList<>();
			for (int j = 0; j < itemsListObj.size(); j++) {
				QuestionnaireSetItems item = itemsListObj.get(j);
				String itemSet = StringUtils.null2String(item.getItemSetting());
				if ("mulscale".equals(topic.getTopicType())) {
					if (!"".equals(itemSet)) {
						List<String> mulList = Arrays.asList(itemSet.split("option-option"));
						List<Map<String, Object>> mulscaleList = new ArrayList<Map<String, Object>>();
						for (int h = 0; h < mulList.size(); h++) {
							Map<String, Object> mulscaleMap = new HashMap<String, Object>();
							mulscaleMap = JsonUtils.readValue(mulList.get(h));
							mulscaleList.add(mulscaleMap);
						}
						item.setList(mulscaleList);
					}
				} else {
					if (!"".equals(itemSet)) {
						Map<String, Object> mapItemSet = new HashMap<String, Object>();
						mapItemSet = JsonUtils.readValue(itemSet);
						item.setMapSet(mapItemSet);
					}
				}
				int itemNo = item.getSortNo();
				if (itemNo != 0) {
					item.setLetter(QuestionnaireUtils.getLetterByNum(itemNo));
				}
				itemsList.add(item);
			}
			topic.setList(itemsList);
			list.add(topic);
		}
		return list;
	}
	
	/**
	 * 获取题库题目信息
	 * 
	 * @param setId
	 *            题库Id
	 * @param userId
	 *            用户ID
	 * @param token
	 *            系统参数：TOKEN
	 * @return 题库题目实体集合
	 */
	public Map<String, Object> getSetTopicListByPage(String setId, String topicType, String topicName, String userId, String token, Pageable pageable, String currentPage) {
		List<QuestionnaireSetTopic> list = new ArrayList<>();
		List<QuestionnaireSetTopic> topicList = new ArrayList<>();
		StringBuffer sql = new StringBuffer();
		sql.append(" SELECT t.ID, t.set_id, t.topic_name, t.topic_name_txt, t.topic_no, t.topic_setting, t.topic_type, t.times FROM oa_questionnaire_set_topic t WHERE t.set_id = :setId");
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("setId", setId);
		if (StringUtils.isNotBlank(topicType)) {
			sql.append(" AND t.topic_type = :topicType");
			paramMap.put("topicType", topicType);
		}
		if (StringUtils.isNotBlank(topicName)) {
			sql.append(" AND t.topic_name_txt LIKE :topicName");
			paramMap.put("topicName", "%"+topicName+"%");
		}
		sql.append(" ORDER BY t.sort_no");
		Page<Map> page = super.findByPageNativeSQL(pageable, sql.toString(), paramMap);
		List<Map> mapList = page.getContent();
		if (CollectionUtils.isNotEmpty(mapList)) {
			for (Map map : mapList) {
				QuestionnaireSetTopic questionnaireSetTopic = new QuestionnaireSetTopic();
				questionnaireSetTopic.setId(map.get("ID").toString());
				questionnaireSetTopic.setSetId(map.get("set_id").toString());
				questionnaireSetTopic.setTopicName(StringUtils.null2String(map.get("topic_name")));
				questionnaireSetTopic.setTopicNameTxt(StringUtils.null2String(map.get("topic_name_txt")));
				questionnaireSetTopic.setTopicNo(StringUtils.null2String(map.get("topic_no")));
				questionnaireSetTopic.setTopicSetting(StringUtils.null2String(map.get("topic_setting")));
				questionnaireSetTopic.setTopicType(StringUtils.null2String(map.get("topic_type")));
				questionnaireSetTopic.setTimes(StringUtils.null2String(map.get("times")));
				topicList.add(questionnaireSetTopic);
			}
		}
		for (int i = 0; i < topicList.size(); i++) {
			QuestionnaireSetTopic topic = topicList.get(i);
			String ruleTopicName = topic.getTopicName();
			if(!"".equals(StringUtils.null2String(ruleTopicName))){
				//ruleTopicName =ruleTopicName.replace("<p>", "").replace("</p>", "");
				topic.setRuleTopicName(ruleTopicName);
			}
			String topicSetting = StringUtils.null2String(topic.getTopicSetting());
			if (!"".equals(topicSetting)) {
				Map<String, Object> mapTopicSet = new HashMap<String, Object>();
				mapTopicSet = JsonUtils.readValue(topicSetting);
				if ("field".equals(topic.getTopicType())) {
					String extensions = "";
					if ("gif".equals(mapTopicSet.get("gif"))) {
						extensions += "gif" + ",";
					}
					if ("png".equals(mapTopicSet.get("png"))) {
						extensions += "png" + ",";
					}
					if ("jpg".equals(mapTopicSet.get("jpg"))) {
						extensions += "jpg" + ",";
					}
					if ("jpeg".equals(mapTopicSet.get("jpeg"))) {
						extensions += "jpeg" + ",";
					}
					if ("bmp".equals(mapTopicSet.get("bmp"))) {
						extensions += "bmp" + ",";
					}
					if ("doc".equals(mapTopicSet.get("doc"))) {
						extensions += "doc" + ",";
					}
					if ("docx".equals(mapTopicSet.get("docx"))) {
						extensions += "docx" + ",";
					}
					if ("pdf".equals(mapTopicSet.get("pdf"))) {
						extensions += "pdf" + ",";
					}
					if ("xls".equals(mapTopicSet.get("xls"))) {
						extensions += "xls" + ",";
					}
					if ("xlsx".equals(mapTopicSet.get("xlsx"))) {
						extensions += "xlsx" + ",";
					}
					if ("ppt".equals(mapTopicSet.get("ppt"))) {
						extensions += "ppt" + ",";
					}
					if ("pptx".equals(mapTopicSet.get("pptx"))) {
						extensions += "pptx" + ",";
					}
					if ("txt".equals(mapTopicSet.get("txt"))) {
						extensions += "txt" + ",";
					}
					if ("rar".equals(mapTopicSet.get("rar"))) {
						extensions += "rar" + ",";
					}
					if ("zip".equals(mapTopicSet.get("zip"))) {
						extensions += "zip" + ",";
					}
					if ("gzip".equals(mapTopicSet.get("gzip"))) {
						extensions += "gzip" + ",";
					}
					if (extensions.endsWith(",")) {
						extensions = extensions.substring(0, extensions.length() - 1);
					}
					if (!"".equals(extensions)) {
						mapTopicSet.put("upload", "true");
					} else {
						mapTopicSet.put("upload", "false");
					}
					mapTopicSet.put("extensions", extensions);
				}
				topic.setSettingMap(mapTopicSet);
			}
			List<QuestionnaireSetItems> itemsListObj = itemDao.getItemsByTopicId(topic.getId());
			List<QuestionnaireSetItems> itemsList = new ArrayList<>();
			for (int j = 0; j < itemsListObj.size(); j++) {
				QuestionnaireSetItems item = itemsListObj.get(j);
				String itemSet = StringUtils.null2String(item.getItemSetting());
				if ("mulscale".equals(topic.getTopicType())) {
					if (!"".equals(itemSet)) {
						List<String> mulList = Arrays.asList(itemSet.split("option-option"));
						List<Map<String, Object>> mulscaleList = new ArrayList<Map<String, Object>>();
						for (int h = 0; h < mulList.size(); h++) {
							Map<String, Object> mulscaleMap = new HashMap<String, Object>();
							mulscaleMap = JsonUtils.readValue(mulList.get(h));
							mulscaleList.add(mulscaleMap);
						}
						item.setList(mulscaleList);
					}
				} else {
					if (!"".equals(itemSet)) {
						Map<String, Object> mapItemSet = new HashMap<String, Object>();
						mapItemSet = JsonUtils.readValue(itemSet);
						item.setMapSet(mapItemSet);
					}
				}
				int itemNo = item.getSortNo();
				if (itemNo != 0) {
					item.setLetter(QuestionnaireUtils.getLetterByNum(itemNo));
				}
				itemsList.add(item);
			}
			topic.setList(itemsList);
			list.add(topic);
		}
		Map<String, Object> resultMap = new HashMap<>();
		resultMap.put("content", list);
		resultMap.put("number", Integer.valueOf(page.getNumber()));
		resultMap.put("numberOfElements", Integer.valueOf(page.getNumberOfElements()));
		resultMap.put("size", Integer.valueOf(page.getSize()));
		resultMap.put("sort", page.getSort());
		resultMap.put("totalElements", Long.valueOf(page.getTotalElements()));
		resultMap.put("totalPages", Integer.valueOf(page.getTotalPages()));
		resultMap.put("currentPage", currentPage);
		return resultMap;
	}

	/**
	 * 根据题库Id查询题库题目数量
	 * 
	 * @param setId
	 *            题库id
	 * @return 题库题目数量
	 */
	public int getSetTopicCount(String setId) {
		List<QuestionnaireSetTopic> topicList = topicDao.getTopicBySetId(setId);
		if (CollectionUtils.isNotEmpty(topicList)) {
			return topicList.size();
		}
		return 0;
	}

}